C++Data StructuresAlgorithmsCompetitive ProgrammingJavaPythonMicroprocessorsGraph TheoryComputer System ArchitectureMachine LearningArtificial IntelligenceData Structures in PythonJavascriptMySQLAndroid DevelopmentAlgorithms in PythonCoding InterviewData ScienceData Structures in JavaObject Oriented DesignLinked ListBinary Trees

Competitive Programming

Adding two numbers using Linked List

Two Sum Problem | Brute Force Approach-1

Two Sum Problem Approach-2

First Bad Version

Jewels and Stones

Addition of two numbers using Linked List


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode* l3 =  (struct ListNode*)malloc(sizeof(struct ListNode));
    l3->val = 0;
    l3->next = NULL;
    struct ListNode* Result = l3;
    unsigned int sum = 0,carry = 0;
    while(l1 != NULL || l2 != NULL){
      if(l2==NULL){
          l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
          l2->next = NULL;
          l2->val = 0;
      }
      if(l1==NULL){
          l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
          l1->next = NULL;
          l1->val = 0;
      }
      sum = l1->val + l2->val;
      int temp = sum;
      if(sum/10 >= 1){
          sum = sum%10;
      }
      else{
          sum = l1->val + l2->val;
      }
      l3->next =  (struct ListNode*)malloc(sizeof(struct ListNode));
      if(sum == 9 && carry == 1){
          l3->next->val = 0;
          carry = 1;
      }
      else{
      l3->next->val = sum + carry;
      l3->next->next = NULL;
      
     if(temp/10 >= 1){
      carry = 1;   
     }
      else{
      carry = 0;
     }
    }
      l1= l1->next;
      l2 = l2->next;
      l3 = l3->next;
  }
    if(carry == 1){
      l3->next =  (struct ListNode*)malloc(sizeof(struct ListNode));
      l3->next->val = 1;
      l3->next->next = NULL;
    }
    Result = Result->next;
    return Result;
}